var app = getApp();
var ajax = require('./ajax.js');
var Config = require('../config.js');

var isExtInited = false;
var sysInfo = undefined;

//初始化app
function initApp(options) {
  var {
    loginSuc,
    sysInfoSuc,
    fetchSysInfo = false, //是否强制获取系统信息
  } = options || {};

  quietLogin(function() {
    loginSuc && loginSuc();
    getSysInfo((sysInfo) => {
      sysInfoSuc && sysInfoSuc(sysInfo);
    }, fetchSysInfo);
  });
}

//读取系统信息
function getSysInfo(cb, fetchSysInfo) {

  if (!fetchSysInfo && sysInfo) {
    return cb && cb(sysInfo);
  }

  wx.getSystemInfo({
    complete: (res) => {
      const {
        windowHeight,
        windowWidth
      } = res;

      sysInfo = res;
      windowHeight && app.setWinHei(windowHeight);
      windowWidth && app.setWinWid(windowWidth);
      cb && cb(res);
    },
  });
}

/**
 * 静默登陆
 */
function quietLogin(cb) {
  //检验登录态是否过期
  wx.checkSession({
    success: function() { //session没有过期
      if (app.getOpenId()) {
        cb && cb();
        return;
      }
      doLogin(cb);
    },
    fail: function() { //session已过期
      doLogin(cb);
    }
  });
}

function doLogin(cb) {
  wx.login({
    success: function(res) {
      // app.getUserInfo(function(userInfo) {
      var params = {
        jscode: res.code
      };
      ajax.P({
        url: '/public/api/user/code2Session',
        data: {
          code: params.jscode
        },
        success: (res,isLoadcb) => {
          var {
            openid
          } = res.data;

          !!openid && app.setOpenId(openid);
          isLoadcb && isLoadcb();
          cb && cb();
        }
      });
      // });
    },
    fail: function() {},
    complete: function() {}
  });

}

function jump(evt) {

  var formId = evt.detail.formId;
  var {
    openType,
    url,
    mustLogin
  } = evt.currentTarget.dataset;

  console.log(evt,openType);

  if (openType == 'navigate' || !openType) {
    openType = 'navigateTo';
  }

  wx[openType]({
    url
  });
  submitForm(formId);
}

//提交表单id
function submitForm(formId) {
  if (!formId) {
    return;
  }
  ajax.P({
    url: '/common/User/addFormId',
    data: {
      openId: app.getOpenId(),
      formId
    },
    success: function (res,isLoadcb) {
      isLoadcb && isLoadcb();
    }
  });
}

//提交支付id
function submitPrepay(prepayId) {
  if (!prepayId) {
    return
  }
  ajax.P({
    url: '/common/User/addPrePayId',
    data: {
      openId: app.getOpenId(),
      prepayId,
    },
    success: function (res, isLoadcb) {
      isLoadcb && isLoadcb();
    }
  });
}

const pageMedhods = ['onLoad', 'onReady', 'onShow', 'onHide', 'onUnload', 'onPullDownRefresh', 'onReachBottom', 'onShareAppMessage', 'onPageScroll'];

function extend(Child, Parent) {
  var F = function() {};
  F.prototype = Parent.prototype;
  Child.prototype = new F();
  Child.prototype.constructor = Child;
  Child.uber = Parent.prototype;
}

//合并两个Page对象
function extendPage(source, obj) {
  if (!source || !obj) {
    return;
  }
  var newObj = {};
  var newData = {};

  Object.assign(newData, source['data']);
  Object.assign(newData, obj['data']);

  Object.assign(newObj, source);
  Object.assign(newObj, obj);

  newObj['data'] = newData;

  pageMedhods.forEach(function(methodName) {
    var sourceFunc = source[methodName];
    var objFunc = obj[methodName];

    if (sourceFunc && objFunc) {
      newObj[methodName] = function(...params) {
        sourceFunc.bind(this)(...params);
        objFunc.bind(this)(...params);
      }
    }
  });

  return newObj;
}

var pageIndex = 0;
var pageList = ['/pages/mPage1/index', '/pages/mPage2/index', '/pages/mPage3/index'];

//跳转到某个自定义页面
function goToPage(pageId) {
  if (!pageId) {
    return;
  }
  var openType = 'navigateTo';
  var maxIndex = pageList.length - 1;
  var tabBar = app.config.tabBar;
  var toBarName;

  if (pageIndex > maxIndex) {
    openType = 'redirectTo';
  }

  if (tabBar) {
    Object.keys(tabBar).some(function(key) {
      if (tabBar[key] == pageId) {
        openType = 'switchTab';
        toBarName = key;
        return true;
      }
    });
  }

  if (openType == 'switchTab') {
    wx[openType]({
      url: '/pages/' + toBarName + '/index'
    });
    pageIndex = 0;
  } else {
    wx[openType]({
      url: pageList[pageIndex > maxIndex ? maxIndex : pageIndex] + '?pageId=' + pageId
    });
    pageIndex++;
  }
}

function goBackPage() {
  pageIndex--;
}

module.exports = {
  initApp,
  quietLogin,
  submitForm,
  jump,
  extend,
  extendPage,
  goToPage,
  goBackPage,
  submitPrepay
};